<template>
	<div class='box'>
		<u-navbar title="加价购活动详情" v-if="Object.keys(routerVal).length"></u-navbar>
		<u-navbar title="新增加价购活动" v-else></u-navbar>
		<u-alert-tips type="warning" v-if="disabled" :title="promotionStatus | promotionStatus" :show-icon="true">
		</u-alert-tips>
		<div>
			<u-form label-position='top' :model="form" ref="uForm">
				<u-form-item prop="promotionName" label="活动名称">
					<div>
						<u-input :disabled="disabled" :custom-style="inputStyle" v-model="form.promotionName" />
					</div>
				</u-form-item>
				<u-form-item label="活动描述">
					<div>
						<u-input :disabled="disabled" :custom-style="inputStyle" v-model="form.promotionDescrib" />
					</div>
				</u-form-item>
				<u-form-item prop="startTime" label="活动时间-开始">
					<u-input style="width: 100%;" disabled @click="clickTime('startTime')" :custom-style="inputStyle"
						v-model="form.startTime" />
				</u-form-item>
				<u-form-item prop="endTime" label="活动时间-结束">
					<u-input style="width: 100%;" disabled @click="clickTime('endTime')" :custom-style="inputStyle"
						v-model="form.endTime" />
				</u-form-item>

				<u-form-item label="购买门槛">
					<div>
						<u-number-box :positive-integer='false' :disabled="disabled" v-model="form.thredshold">
						</u-number-box>
						<div class='tips'>
							消费达到当前金额可以参与加价购。
						</div>
					</div>
				</u-form-item>
				<u-form-item label="适用范围">
					<div>
						<u-radio-group v-model="form.scopeType" @change="radioGroupChange">
							<u-radio active-color='#333' @change="radioChange" v-for="(item, index) in useTypeList"
								:key="index" :name="item.value" :disabled="item.disabled">
								{{ item.name }}
							</u-radio>
						</u-radio-group>
					</div>
				</u-form-item>



				<div class='select-goods' v-if='!disabled' @click='selectGoods'>
					选择商品
				</div>
				<!-- 新选择 商品部分 -->
				<div class='goods-flex' v-if="selectedGoodsList.length">
					<div class="goods-item flex" v-for="(item, index) in selectedGoodsList" :key="index">
						<div>
							<u-image width="200" height="200" :src="item.thumbnail"></u-image>
						</div>
						<div class="goods-name">
							<div class="wes-2">{{ item.goodsName }}</div>
							<div>库存：{{ item.quantity }}</div>
							<div class="goods-price">
								价格：¥ <u-number-box v-model="item.price" :disabled="disabled"></u-number-box>
							</div>
							<div class="delete" @click='selectedGoodsList.splice(index, 1)'>
								删除
							</div>
							<u-line color="#ededed" />
						</div>

					</div>
				</div>


				<!-- 之前选择 商品部分 -->
				<div class='goods-flex'>
					<div class="goods-item flex" v-for="(item, index) in form.promotionGoodsList" :key="index">
						<div>
							<u-image width="200" height="200" :src="item.thumbnail"></u-image>
						</div>
						<div class="goods-name">
							<div class="wes-2">{{ item.goodsName }}</div>
							<div>库存：{{ item.quantity }}</div>
							<div class="goods-price">
								价格：¥ <u-number-box v-model="item.price" :disabled="disabled"></u-number-box>
							</div>
							<div class="delete" @click='form.promotionGoodsList.splice(index, 1)'>
								删除
							</div>
							<u-line color="#ededed" />
						</div>
					</div>
				</div>
				<!-- 结束 -->



				<div class='submit' v-if='!disabled' @click='submit'>
					保存/提交
				</div>

			</u-form>
			<!-- 时间选择器 -->
			<u-picker mode="time" :disabled="disabled" :start-year="minStratTime" @confirm="callbackTime"
				v-model="showTimePicker" :params="params"></u-picker>

		</div>
	</div>
</template>
<script>
import {
	savePinTuan,
	editPinTuan,
	getFullDiscountDetail,
	getShopCouponList,


	addGoodsByIdAsync,
	setAddGoodsByIdAsync
} from "@/api/promotion";
import {
	goodsGoodsSkuList
} from '@/api/goods.js'
import storage from "@/utils/storage.js"; //缓存
export default {
	data() {
		return {
			useTypeList: [{
				name: '指定商品',
				value: 'PORTION_GOODS',
				disabled: false
			}],
			// 优惠方式
			discountTypeList: [{
				name: '减现金',
				value: 'fullMinusFlag',
				disabled: false
			},
			{
				name: '打折',
				value: 'fullRateFlag',
				disabled: false
			},
			],
			// 赠送列表
			freeList: [{
				name: '免邮费',
				value: "freeFreightFlag",
				checked: false,
				disabled: false
			}, {
				name: '送优惠券',
				checked: false,
				value: "couponFlag",
				disabled: false
			}, {
				name: '送赠品',
				checked: false,
				value: "giftFlag",
				disabled: false
			}],
			times: "",
			giftList: [], // 送赠品列表
			couponList: [], // 店铺优惠券列表
			params: {
				year: true,
				month: true,
				day: true,
				hour: true,
				minute: true,
				second: false
			},
			showTimePicker: false, // 显示时间选择器
			disabled: false, // 表单input禁用状态
			promotionStatus: "", // 活动状态
			selectedGoodsList: [], //当前选择的商品列表
			form: {
				"endTime": "",
				"fullMoney": 0,
				"huangouRule": "",
				"promotionDescrib": "",
				"promotionGoodsList": [],
				"promotionName": "",
				"scopeId": "",
				"scopeType": "",
				"startTime": "",
				"storeId": "",
				"storeName": "",
				"thredshold": 0
			},

			rules: {
				promotionName: [{
					required: true,
					message: "活动名称不能为空"
				}],
				startTime: [{
					required: true,
					message: "请选择活动时间"
				}],
				endTime: [{
					required: true,
					message: "请选择结束时间"
				}],
			},
			submitLoading: false, // 添加或编辑提交状态
			options: {
				// 不可选取时间
				disabledDate(date) {
					return date && date.valueOf() < Date.now() - 86400000;
				},
			},
			timeType: "",
			inputStyle: {
				background: "#f7f7f7",
				"padding-left": "20rpx",
				"border-radius": "10rpx",
			},
			minStratTime: new Date().getFullYear(),
			routerVal: "",

		}
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	async mounted() {
		if (Object.keys(this.routerVal).length) {
			await this.init();
		}
	},
	onLoad(options) {
		this.routerVal = options
	},
	onShow() {
		const goodsModal = {
			"categoryPath": "",
			"endTime": "",
			"goodsId": "",
			"goodsName": "",
			"goodsType": "",
			"isHuangou": true,
			"limitNum": 0,
			"num": 0,
			"originalPrice": 0,
			"points": 0,
			"price": 0,
			"promotionId": "",
			"promotionType": "",
			"quantity": 0,
			"scopeId": "",
			"scopeType": "",
			"skuId": "",
			"startTime": "",
			"storeId": "",
			"storeName": "",
			"threshold": 0,
			"thumbnail": "",
			"title": ""
		}
		uni.$on("selectedGoods", res => {
			let modal = this.form.promotionGoodsList[0]
			this.selectedGoodsList = res.map(item => {
				Object.keys(item).forEach(newKey => {
					if (Object.keys(goodsModal).indexOf(newKey) === -1) {
						delete item[newKey]
					}
				})
				return {
					...item,
					skuId: item.id
				}
			})
			uni.$off('selectedGoods'); // 清除监听
		})
	},
	methods: {
		checkboxGroupChange(val) {
			console.log(val)
		},
		checkboxChange(val) {
			console.log(val)
		},
		radioGroupChange() { },
		radioChange() {

		},
		// 赠送选项是否是true
		isCheck(val) {
			return this.freeList.find(item => {
				return item.value == val && item.checked
			})
		},

		// 选择商品
		selectGoods() {
			// 最新选择的商品传给商品列表页面
			const ids = this.selectedGoodsList.map(item => {
				return item.id || item.skuId
			})
			uni.navigateTo({
				url: `/pages/goods/skuList?selected=1&ids=${ids}`
			})
		},

		// 初始化满额信息
		async init() {
			uni.showLoading({
				title: '加载中'
			})
			const res = await addGoodsByIdAsync(this.routerVal.id)
			uni.hideLoading()
			if (res.data.success) {
				this.form = res.data.result
				console.log(this.form);
			}
		},

		// 修改/保存满额
		submit() {
			this.$refs.uForm.validate(async (valid) => {
				if (valid) {
					delete this.form.promotionStatus
					this.form.promotionGoodsList = [
						...this.form.promotionGoodsList,
						...this.selectedGoodsList
					]
					const res = await setAddGoodsByIdAsync(this.form)
					console.log(res);
					if (res.data.success) {
						uni.showToast({
							title: "修改成功",
							duration: 1000,
							icon: "none",
						});
						uni.navigateTo({
							url: '/pages/goods/promotion/addGoodsOrder/list'
						})
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none"
						})
					}
				} else {
					console.log('验证失败');
				}
			});
		},

		clickTime(type) {
			if (this.disabled) return
			this.showTimePicker = true
			this.timeType = type
		},
		// 选择器回调时间
		callbackTime(val) {
			const time = `${val.year}-${val.month}-${val.day} ${val.hour}:${val.minute}:00`
			this.form[this.timeType] = time
		}
	}
}
</script>
<style scoped lang="scss">
.box {
	padding: 16rpx;
	padding-bottom: 100rpx;
}



.tips {
	font-size: 24rpx;
	color: #999;
	margin: 20rpx 0;
	line-height: 1.5;
}

.select-goods {
	background: #333;
	color: #fff;
	width: 200rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	border-radius: 10rpx;
	margin: 20rpx 0;
}

.goods-item {
	padding: 32rpx 0;
}

.goods-price {
	text-align: right;
}

.goods-name {
	flex: 2;
	margin-left: 20rpx;
}

.goods-total {
	display: flex;
	flex-direction: column;
	margin-top: 20rpx;

	>.flex {
		justify-content: space-between;
		margin: 10rpx 0;
		line-height: 1.75;

		>div:nth-of-type(1) {
			font-size: 24rpx;
			color: #999;
		}

		>div:nth-of-type(2) {
			font-weight: bold;

			>span {
				font-size: 40rpx;
				margin-left: 10rpx;
			}
		}

		>div {
			margin: 0 4rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}
}

.submit {
	position: fixed;
	bottom: 10rpx;
	width: 90%;
	left: 5%;
	z-index: 99;
}

.delete {
	color: $main-color;
	margin: 20rpx 0;
	text-align: right;
}

.item-title {
	color: #333;
	font-size: 28rpx;
	margin-top: 20rpx;
}
</style>
